package cn.itcast.dtx.txmsgdemo.bank2.message;

import cn.itcast.dtx.txmsgdemo.bank2.model.AccountChangeEvent;
import cn.itcast.dtx.txmsgdemo.bank2.service.AccountInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 **/
@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "txmsg_bank2", topic = "tx_msg")
public class TxmsgConsumer implements RocketMQListener<String> {

    @Autowired
    AccountInfoService accountInfoService;

    @Autowired
    private ObjectMapper json;

    /**
     * 接收消息
     * @param message 消息对象
     */
    @SneakyThrows
    @Override
    public void onMessage(String message) {
        log.info("开始消费消息:{}",message);
        //解析 message，转成 AccountChangeEvent
        Message<String> msg = json.readValue(message, Message.class);
        String jsonStr = json.writeValueAsString(msg.getPayload());
        Map<String, Object> map = json.readValue(jsonStr, Map.class);
        Object obj = map.get("accountChange");
        AccountChangeEvent accountChangeEvent = json.readValue(json.writeValueAsString(obj), AccountChangeEvent.class);
        // 设置账号为李四
        accountChangeEvent.setAccountNo("2");
        // 更新本地账户，增加金额
        accountInfoService.addAccountInfoBalance(accountChangeEvent);
        log.info("收款成功");
    }

}
